package easy.netty.net.core;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author cengy
 */
public class Connector
        extends AbsIoService
        implements IoService {

    private static final Logger
            logger = LoggerFactory.getLogger(Connector.class);

    protected Bootstrap bootstrap;
    protected EventLoopGroup workerGroup;

    public Connector(Endpoint endpoint) {
        super(endpoint);
    }

    @Override
    public void open() {
        final IoConf netConf = endpoint.getIoConf();
        try {
            if (null == netConf) {
                throw new RuntimeException("netConf is null");
            }

            bootstrap = new Bootstrap();
            workerGroup = new NioEventLoopGroup(netConf.getWorkerThreadNum());

            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(endpoint);

            Map<String, Object> options = new HashMap(netConf.getOptions());
            Object option = options.remove(ChannelOption.CONNECT_TIMEOUT_MILLIS.name().toLowerCase());
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    (null == option || !(option instanceof Integer)) ? 5000 : Integer.valueOf(options.toString()));

            boolean tcpNoDelayOption = false;
            boolean soKeepAliveOption = false;

            for (Map.Entry<String, Object> optionSet : options.entrySet()) {
                ChannelOption op = ChannelOption.valueOf(optionSet.getKey().toUpperCase());
                if (null == op) continue;
                bootstrap.option(op, optionSet.getValue());
                if (op == ChannelOption.TCP_NODELAY) {
                    tcpNoDelayOption = true;
                }

                if (op == ChannelOption.SO_KEEPALIVE) {
                    soKeepAliveOption = true;
                }
            }

            if (!tcpNoDelayOption)
                bootstrap.option(ChannelOption.TCP_NODELAY, true);

            if (!soKeepAliveOption)
                bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

            bootstrap.remoteAddress(new InetSocketAddress(netConf.getIp(), netConf.getPort()));
            ChannelFuture future = bootstrap.connect().sync();
            if (future.isSuccess()) {
                endpoint.setChannel(future.channel());
                logger.info("Successfully Connect server {}:{}",
                        netConf.getIp(), netConf.getPort());
            }
        } catch (Exception e) {
            logger.error("connector start failure, err=", e.toString(), e);
            if (null != netConf)
                tryAgain();
        }
    }

    protected void tryAgain() {
        try {
            logger.info("Try connect after 5's");
            TimeUnit.SECONDS.sleep(5);
            open();
        } catch (InterruptedException ignore) {
            // ignore
        }
    }

    @Override
    public void close() {
        tryClose();
    }

    protected void tryClose() {
        try {
            if (null != workerGroup)
                workerGroup.shutdownGracefully().sync();
        } catch (Exception e) {
            logger.error("connector close caught exception", e);
        }
    }

}
